<template>
  <AdminLayout title="添加产品" subtitle="创建新的产品">
    <div class="max-w-4xl">
      <!-- 进度条 -->
      <div class="mb-8">
        <div class="flex items-center justify-between mb-4">
          <div class="flex items-center space-x-4">
            <div v-for="(step, index) in steps" :key="index" class="flex items-center">
              <div 
                class="flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium transition-colors duration-200"
                :class="getStepClasses(index)"
              >
                <span v-if="index < currentStep" class="text-white">✓</span>
                <span v-else>{{ index + 1 }}</span>
              </div>
              <span 
                class="ml-2 text-sm font-medium transition-colors duration-200"
                :class="index <= currentStep ? 'text-gray-900' : 'text-gray-500'"
              >
                {{ step.title }}
              </span>
              <div 
                v-if="index < steps.length - 1" 
                class="w-8 h-0.5 mx-4 transition-colors duration-200"
                :class="index < currentStep ? 'bg-gray-900' : 'bg-gray-300'"
              ></div>
            </div>
          </div>
          <div class="text-sm text-gray-500">
            步骤 {{ currentStep + 1 }} / {{ steps.length }}
          </div>
        </div>
        
        <!-- 进度条 -->
        <div class="w-full bg-gray-200 rounded-full h-2">
          <div 
            class="bg-gray-900 h-2 rounded-full transition-all duration-300 ease-out"
            :style="{ width: `${((currentStep + 1) / steps.length) * 100}%` }"
          ></div>
        </div>
      </div>

      <form @submit.prevent="submit" class="space-y-6">
        <!-- 步骤1: 基本信息 -->
        <div v-show="currentStep === 0" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">基本信息</h3>
            <p class="mt-1 text-sm text-gray-500">填写产品的基本信息</p>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 产品名称 -->
            <div>
              <label for="name" class="block text-sm font-medium text-gray-700">
                产品名称 <span class="text-red-500">*</span>
              </label>
              <input 
                id="name"
                v-model="form.name"
                type="text" 
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.name }"
                placeholder="请输入产品名称"
              />
              <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
            </div>

            <!-- 产品别名 -->
            <div>
              <label for="slug" class="block text-sm font-medium text-gray-700">
                产品别名 <span class="text-red-500">*</span>
              </label>
              <input 
                id="slug"
                v-model="form.slug"
                type="text" 
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.slug }"
                placeholder="请输入产品别名（用于URL）"
              />
              <p v-if="errors.slug" class="mt-1 text-sm text-red-600">{{ errors.slug }}</p>
              <p class="mt-1 text-sm text-gray-500">用于URL的标识符，只能包含字母、数字和连字符</p>
            </div>

            <!-- 产品SKU -->
            <div>
              <label for="sku" class="block text-sm font-medium text-gray-700">
                产品SKU <span class="text-red-500">*</span>
              </label>
              <input 
                id="sku"
                v-model="form.sku"
                type="text" 
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.sku }"
                placeholder="请输入产品SKU（库存单位）"
              />
              <p v-if="errors.sku" class="mt-1 text-sm text-red-600">{{ errors.sku }}</p>
              <p class="mt-1 text-sm text-gray-500">产品的唯一标识码，用于库存管理</p>
            </div>

            <!-- 产品简短描述 -->
            <div>
              <label for="description" class="block text-sm font-medium text-gray-700">
                简短描述
              </label>
              <textarea 
                id="description"
                v-model="form.description"
                rows="3"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.description }"
                placeholder="请输入产品简短描述（用于列表页展示）"
              ></textarea>
              <p v-if="errors.description" class="mt-1 text-sm text-red-600">{{ errors.description }}</p>
            </div>

            <!-- 详细描述 -->
            <div>
              <label for="long_description" class="block text-sm font-medium text-gray-700">
                详细描述
              </label>
              <textarea 
                id="long_description"
                v-model="form.long_description"
                rows="8"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.long_description }"
                placeholder="请输入产品详细描述（支持多行文本）"
              ></textarea>
              <p v-if="errors.long_description" class="mt-1 text-sm text-red-600">{{ errors.long_description }}</p>
              <p class="mt-1 text-sm text-gray-500">产品的详细介绍，将在产品详情页展示</p>
            </div>

            <!-- 产品特性 -->
            <div>
              <label class="block text-sm font-medium text-gray-700">
                产品特性
              </label>
              <div class="mt-2 space-y-2">
                <div v-for="(feature, index) in form.features" :key="index" class="flex gap-2">
                  <input 
                    v-model="form.features[index]"
                    type="text"
                    class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                    placeholder="请输入产品特性"
                  />
                  <button 
                    type="button"
                    @click="removeFeature(index)"
                    class="px-3 py-2 text-sm text-red-600 hover:text-red-700"
                  >
                    删除
                  </button>
                </div>
              </div>
              <button 
                type="button"
                @click="addFeature"
                class="mt-2 text-sm text-gray-600 hover:text-gray-900"
              >
                + 添加特性
              </button>
              <p class="mt-1 text-sm text-gray-500">产品的核心特点，以列表形式展示</p>
            </div>

            <!-- 技术规格 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                技术规格
              </label>
              <div class="space-y-4">
                <div v-for="(spec, specIndex) in form.technical_specs" :key="specIndex" class="border border-gray-200 rounded-md p-4">
                  <div class="flex items-center justify-between mb-3">
                    <input 
                      v-model="spec.category"
                      type="text"
                      class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                      placeholder="规格分类（如：显示屏、芯片与性能）"
                    />
                    <button 
                      type="button"
                      @click="removeSpecCategory(specIndex)"
                      class="ml-2 px-3 py-2 text-sm text-red-600 hover:text-red-700"
                    >
                      删除分类
                    </button>
                  </div>
                  <div class="space-y-2">
                    <div v-for="(item, itemIndex) in spec.items" :key="itemIndex" class="flex gap-2">
                      <input 
                        v-model="item.name"
                        type="text"
                        class="w-1/3 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        placeholder="参数名称"
                      />
                      <input 
                        v-model="item.value"
                        type="text"
                        class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        placeholder="参数值"
                      />
                      <button 
                        type="button"
                        @click="removeSpecItem(specIndex, itemIndex)"
                        class="px-3 py-2 text-sm text-red-600 hover:text-red-700"
                      >
                        删除
                      </button>
                    </div>
                    <button 
                      type="button"
                      @click="addSpecItem(specIndex)"
                      class="text-sm text-gray-600 hover:text-gray-900"
                    >
                      + 添加参数
                    </button>
                  </div>
                </div>
              </div>
              <button 
                type="button"
                @click="addSpecCategory"
                class="mt-3 text-sm text-gray-600 hover:text-gray-900"
              >
                + 添加规格分类
              </button>
              <p class="mt-1 text-sm text-gray-500">产品的技术参数，按分类组织展示</p>
            </div>
          </div>
          <!-- 价格与状态（并入基础信息） -->
          <div class="px-6 pb-6 space-y-6">
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <div>
                <label for="price" class="block text-sm font-medium text-gray-700">售价 <span class="text-red-500">*</span></label>
                <input id="price" v-model.number="form.price" type="number" step="0.01" min="0" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm" :class="{ 'border-red-300': errors.price }" placeholder="0.00" />
                <p v-if="errors.price" class="mt-1 text-sm text-red-600">{{ errors.price }}</p>
              </div>
              <div>
                <label for="compare_price" class="block text-sm font-medium text-gray-700">原价</label>
                <input id="compare_price" v-model.number="form.compare_price" type="number" step="0.01" min="0" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm" :class="{ 'border-red-300': errors.compare_price }" placeholder="0.00" />
                <p v-if="errors.compare_price" class="mt-1 text-sm text-red-600">{{ errors.compare_price }}</p>
                <p class="mt-1 text-xs text-gray-500">只有商品有降价时才填写原价，留空表示无折扣</p>
              </div>
            </div>

            <div class="space-y-4">
              <div class="flex items-center">
                <input id="is_active" v-model="form.is_active" type="checkbox" class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded" />
                <label for="is_active" class="ml-2 block text-sm text-gray-900">启用此产品</label>
              </div>
              <div class="flex items-center">
                <input id="is_featured" v-model="form.is_featured" type="checkbox" class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded" />
                <label for="is_featured" class="ml-2 block text-sm text-gray-900">设为推荐产品</label>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤2: 价格和库存 -->
        <div v-show="currentStep === 1" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">价格和库存</h3>
            <p class="mt-1 text-sm text-gray-500">设置产品的基础价格和库存信息</p>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 价格信息 -->
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <div>
                <label for="price" class="block text-sm font-medium text-gray-700">
                  售价 <span class="text-red-500">*</span>
                </label>
                <input 
                  id="price"
                  v-model.number="form.price"
                  type="number" 
                  step="0.01"
                  min="0"
                  class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :class="{ 'border-red-300': errors.price }"
                  placeholder="0.00"
                />
                <p v-if="errors.price" class="mt-1 text-sm text-red-600">{{ errors.price }}</p>
              </div>

              <div>
                <label for="compare_price" class="block text-sm font-medium text-gray-700">
                  原价
                </label>
                <input 
                  id="compare_price"
                  v-model.number="form.compare_price"
                  type="number" 
                  step="0.01"
                  min="0"
                  class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :class="{ 'border-red-300': errors.compare_price }"
                  placeholder="0.00"
                />
                <p v-if="errors.compare_price" class="mt-1 text-sm text-red-600">{{ errors.compare_price }}</p>
                <p class="mt-1 text-xs text-gray-500">
                  只有商品有降价时才填写原价，留空表示无折扣
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤2: 分类和模板 -->
        <div v-show="currentStep === 1" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">分类和模板</h3>
            <p class="mt-1 text-sm text-gray-500">选择产品分类和规格模板</p>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 产品分类 -->
            <div>
              <label class="block text-sm font-medium text-gray-700">
                产品分类
              </label>
              <div class="mt-2 space-y-2">
                <div v-for="category in categories" :key="category.id" class="flex items-center">
                  <input 
                    :id="`category_${category.id}`"
                    v-model="form.category_ids"
                    type="checkbox" 
                    :value="category.id"
                    class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                  />
                  <label :for="`category_${category.id}`" class="ml-2 block text-sm text-gray-900">
                    {{ category.name }}
                  </label>
                </div>
              </div>
              <p v-if="errors.category_ids" class="mt-1 text-sm text-red-600">{{ errors.category_ids }}</p>
            </div>

            <!-- 产品类型 -->
            <div>
              <label class="block text-sm font-medium text-gray-700">
                产品类型 <span class="text-red-500">*</span>
              </label>
              <div class="mt-2 space-y-2">
                <div class="flex items-center">
                  <input 
                    id="product_type_single"
                    v-model="form.product_type"
                    type="radio" 
                    value="single"
                    class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300"
                  />
                  <label for="product_type_single" class="ml-2 block text-sm text-gray-900">
                    单规格产品（只有一个规格）
                  </label>
                </div>
                <div class="flex items-center">
                  <input 
                    id="product_type_multi"
                    v-model="form.product_type"
                    type="radio" 
                    value="multi_variant"
                    class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300"
                  />
                  <label for="product_type_multi" class="ml-2 block text-sm text-gray-900">
                    多规格产品（有多个规格型号）
                  </label>
                </div>
              </div>
              <p v-if="errors.product_type" class="mt-1 text-sm text-red-600">{{ errors.product_type }}</p>
            </div>

            <!-- 多规格配置提示 -->
            <div v-if="form.product_type === 'multi_variant' && form.category_ids.length === 0" class="border-t border-gray-200 pt-6">
              <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div class="flex">
                  <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>
                  <div class="ml-3">
                    <h3 class="text-sm font-medium text-blue-800">
                      请先选择产品分类
                    </h3>
                    <div class="mt-2 text-sm text-blue-700">
                      <p>选择产品分类后，系统将根据分类为您筛选合适的规格模板，包括该分类的专用模板和全局模板。</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 多规格配置 -->
            <div v-if="form.product_type === 'multi_variant' && form.category_ids.length > 0" class="space-y-6">
              <div class="border-t border-gray-200 pt-6">
                <h4 class="text-lg font-medium text-gray-900 mb-4">规格配置</h4>
                
                <!-- 规格模板选择 -->
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700">
                      选择规格模板
                    </label>
                    <div class="mt-2 space-y-3">
                      <div v-for="template in filteredTemplates" :key="template.id" 
                           class="relative flex items-start p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
                           :class="{ 'ring-2 ring-gray-900 bg-gray-50': selectedTemplate?.id === template.id }"
                           @click="selectTemplate(template)">
                        <div class="flex items-center h-5">
                          <input 
                            :id="`template_${template.id}`"
                            v-model="selectedTemplate"
                            :value="template"
                            type="radio" 
                            class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300"
                          />
                        </div>
                        <div class="ml-3 flex-1">
                          <div class="flex items-center justify-between">
                            <label :for="`template_${template.id}`" class="font-medium text-gray-900">
                              {{ template.name }}
                            </label>
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                  :class="template.category_id ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'">
                              {{ template.category_name }}
                            </span>
                          </div>
                          <p v-if="template.description" class="text-sm text-gray-500 mt-1">
                            {{ template.description }}
                          </p>
                          <p class="text-xs text-gray-400 mt-1">
                            包含 {{ template.attributes_config?.length || 0 }} 个规格属性
                          </p>
                        </div>
                      </div>
                    </div>
                    <p class="mt-2 text-sm text-gray-500">
                      根据已选分类筛选的规格模板，包含该分类专用模板和全局模板
                    </p>
                  </div>
                </div>

                <!-- 分隔线 -->
                <div class="relative my-6">
                  <div class="absolute inset-0 flex items-center">
                    <div class="w-full border-t border-gray-300" />
                  </div>
                  <div class="relative flex justify-center text-sm">
                    <span class="px-2 bg-white text-gray-500">或</span>
                  </div>
                </div>

                <!-- 手动规格属性选择 -->
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700">
                      手动选择规格属性
                    </label>
                    <div class="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                      <div v-for="attribute in availableAttributes" :key="attribute.id" 
                           class="relative flex items-start">
                        <div class="flex items-center h-5">
                          <input 
                            :id="`attribute_${attribute.id}`"
                            v-model="selectedAttributes"
                            :value="attribute.id"
                            type="checkbox" 
                            class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                          />
                        </div>
                        <div class="ml-3 text-sm">
                          <label :for="`attribute_${attribute.id}`" class="font-medium text-gray-700">
                            {{ attribute.name }}
                          </label>
                          <p class="text-gray-500">{{ attribute.type_label }}</p>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 规格型号生成（移动到步骤3，这里隐藏） -->
                  <div v-if="false">
                    <div class="flex items-center justify-between">
                      <label class="block text-sm font-medium text-gray-700">
                        规格型号
                      </label>
                      <button 
                        type="button"
                        @click="generateVariants"
                        class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200"
                      >
                        <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                        {{ selectedTemplate ? '从模板生成规格型号' : '生成规格型号' }}
                      </button>
                    </div>
                    
                    <div v-if="generatedVariants.length > 0" class="mt-4 space-y-3">
                      <div v-for="(variant, index) in generatedVariants" :key="index" 
                           class="border border-gray-200 rounded-lg p-4">
                        <div class="flex items-center justify-between mb-3">
                          <h5 class="text-sm font-medium text-gray-900">
                            规格型号 {{ index + 1 }}
                          </h5>
                          <button 
                            type="button"
                            @click="removeVariant(index)"
                            class="text-red-600 hover:text-red-900 transition-colors duration-200"
                          >
                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          </button>
                        </div>
                        
                  <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    <div v-for="spec in variant.specifications" :key="spec.attribute_id" class="space-y-2">
                      <label class="block text-xs font-medium text-gray-700">
                        {{ spec.attribute_name || getAttributeName(spec.attribute_id) }}
                      </label>
                      <input 
                        v-model="spec.value"
                        type="text" 
                        readonly
                        class="block w-full border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-600 text-sm cursor-not-allowed"
                        :placeholder="`输入${spec.attribute_name || getAttributeName(spec.attribute_id)}值`"
                      />
                    </div>
                  </div>
                        
                        <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-3">
                     <div>
                       <label class="block text-xs font-medium text-gray-700">SKU</label>
                       <input 
                         v-model="variant.sku"
                         type="text" 
                         class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                         placeholder="留空则自动生成"
                       />
                       <p class="mt-1 text-xs text-gray-500">留空将自动生成为：产品SKU-01、产品SKU-02...</p>
                     </div>
                          <div>
                            <label class="block text-xs font-medium text-gray-700">价格</label>
                            <input 
                              v-model.number="variant.price"
                              type="number" 
                              step="0.01"
                              min="0"
                              class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                              placeholder="0.00"
                            />
                          </div>
                          <div>
                            <label class="block text-xs font-medium text-gray-700">规格型号库存</label>
                            <input 
                              v-model.number="variant.stock_quantity"
                              type="number" 
                              min="0"
                              class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                              placeholder="0"
                            />
                            <p class="mt-1 text-xs text-gray-500">此规格型号的库存数量</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 库存数量 -->
            <div v-if="form.product_type === 'single'">
              <label for="stock_quantity" class="block text-sm font-medium text-gray-700">
                库存数量
              </label>
              <input 
                id="stock_quantity"
                v-model.number="form.stock_quantity"
                type="number" 
                min="0"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.stock_quantity }"
                placeholder="0"
              />
              <p v-if="errors.stock_quantity" class="mt-1 text-sm text-red-600">{{ errors.stock_quantity }}</p>
              <p class="mt-1 text-sm text-gray-500">单规格产品的库存数量</p>
            </div>

            <!-- 多规格产品总库存显示 -->
            <div v-else-if="form.product_type === 'multi_variant' && generatedVariants.length > 0" class="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <div class="flex items-center justify-between text-sm">
                <div class="flex items-center space-x-4">
                  <span class="text-gray-600">总库存：<span class="font-medium text-gray-900">{{ variantStockStats.total }}</span> 件</span>
                  <span class="text-gray-600">规格型号：<span class="font-medium text-gray-900">{{ variantStockStats.variants }}</span> 个</span>
                </div>
                <div class="flex items-center space-x-3 text-xs">
                  <span class="text-green-600">{{ variantStockStats.inStock }} 有库存</span>
                  <span class="text-red-600">{{ variantStockStats.outOfStock }} 缺货</span>
                  <span class="text-yellow-600">{{ variantStockStats.lowStock }} 低库存</span>
                </div>
              </div>
            </div>


            <!-- 状态选项 -->
            <div class="space-y-4">
              <div class="flex items-center">
                <input 
                  id="is_active"
                  v-model="form.is_active"
                  type="checkbox" 
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label for="is_active" class="ml-2 block text-sm text-gray-900">
                  启用此产品
                </label>
              </div>
              
              <div class="flex items-center">
                <input 
                  id="is_featured"
                  v-model="form.is_featured"
                  type="checkbox" 
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label for="is_featured" class="ml-2 block text-sm text-gray-900">
                  设为推荐产品
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤3: 规格型号 -->
        <div v-show="currentStep === 2" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">规格型号</h3>
            <p class="mt-1 text-sm text-gray-500">生成和管理产品规格型号</p>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 规格型号生成 -->
            <div v-if="form.product_type === 'multi_variant'">
              <div class="flex items-center justify-between">
                <label class="block text-sm font-medium text-gray-700">
                  规格型号
                </label>
                <button 
                  type="button"
                  @click="generateVariants"
                  class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200"
                >
                  <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  {{ selectedTemplate ? '从模板生成规格型号' : '生成规格型号' }}
                </button>
              </div>
              
              <div v-if="generatedVariants.length > 0" class="mt-4 space-y-3">
                <div v-for="(variant, index) in generatedVariants" :key="index" 
                     class="border border-gray-200 rounded-lg p-4">
                  <div class="flex items-center justify-between mb-3">
                    <h5 class="text-sm font-medium text-gray-900">
                      规格型号 {{ index + 1 }}
                    </h5>
                    <button 
                      type="button"
                      @click="removeVariant(index)"
                      class="text-red-600 hover:text-red-900 transition-colors duration-200"
                    >
                      <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                  
                  <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    <div v-for="spec in variant.specifications" :key="spec.attribute_id" class="space-y-2">
                      <label class="block text-xs font-medium text-gray-700">
                        {{ spec.attribute_name || getAttributeName(spec.attribute_id) }}
                      </label>
                      <input 
                        v-model="spec.value"
                        type="text" 
                        readonly
                        class="block w-full border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-600 text-sm cursor-not-allowed"
                        :placeholder="`输入${spec.attribute_name || getAttributeName(spec.attribute_id)}值`"
                      />
                    </div>
                  </div>
                  
                  <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-3">
                    <div>
                      <label class="block text-xs font-medium text-gray-700">SKU</label>
                      <input 
                        v-model="variant.sku"
                        type="text" 
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        placeholder="留空则自动生成"
                      />
                      <p class="mt-1 text-xs text-gray-500">留空将自动生成为:产品SKU-01、产品SKU-02...</p>
                    </div>
                    <div>
                      <label class="block text-xs font-medium text-gray-700">价格</label>
                      <input 
                        v-model.number="variant.price"
                        type="number" 
                        step="0.01"
                        min="0"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        placeholder="0.00"
                      />
                    </div>
                    <div>
                      <label class="block text-xs font-medium text-gray-700">规格型号库存</label>
                      <input 
                        v-model.number="variant.stock_quantity"
                        type="number" 
                        min="0"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        placeholder="0"
                      />
                      <p class="mt-1 text-xs text-gray-500">此规格型号的库存数量</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 单规格产品库存 -->
            <div v-else-if="form.product_type === 'single'">
              <div>
                <label for="stock_quantity" class="block text-sm font-medium text-gray-700">
                  库存数量
                </label>
                <input 
                  id="stock_quantity"
                  v-model.number="form.stock_quantity"
                  type="number" 
                  min="0"
                  class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :class="{ 'border-red-300': errors.stock_quantity }"
                  placeholder="0"
                />
                <p v-if="errors.stock_quantity" class="mt-1 text-sm text-red-600">{{ errors.stock_quantity }}</p>
                <p class="mt-1 text-sm text-gray-500">单规格产品的库存数量</p>
              </div>
            </div>

            <!-- 多规格产品总库存显示 -->
            <div v-if="form.product_type === 'multi_variant' && generatedVariants.length > 0" class="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <div class="flex items-center justify-between text-sm">
                <div class="flex items-center space-x-4">
                  <span class="text-gray-600">总库存：<span class="font-medium text-gray-900">{{ variantStockStats.total }}</span> 件</span>
                  <span class="text-gray-600">规格型号：<span class="font-medium text-gray-900">{{ variantStockStats.variants }}</span> 个</span>
                </div>
                <div class="flex items-center space-x-3 text-xs">
                  <span class="text-green-600">{{ variantStockStats.inStock }} 有库存</span>
                  <span class="text-red-600">{{ variantStockStats.outOfStock }} 缺货</span>
                  <span class="text-yellow-600">{{ variantStockStats.lowStock }} 低库存</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 状态设置已并入基础信息，此块隐藏 -->
        <div v-show="false" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">状态设置</h3>
            <p class="mt-1 text-sm text-gray-500">设置产品的发布状态和推荐状态</p>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 状态选项 -->
            <div class="space-y-4">
              <div class="flex items-center">
                <input 
                  id="is_active"
                  v-model="form.is_active"
                  type="checkbox" 
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label for="is_active" class="ml-2 block text-sm text-gray-900">
                  启用此产品
                </label>
              </div>
              
              <div class="flex items-center">
                <input 
                  id="is_featured"
                  v-model="form.is_featured"
                  type="checkbox" 
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label for="is_featured" class="ml-2 block text-sm text-gray-900">
                  设为推荐产品
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 图片管理（新建时提示保存后上传） -->
        <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">产品图片</h3>
            <p class="mt-1 text-sm text-gray-500">系统支持产品多图，创建成功后可在编辑页上传与管理。</p>
          </div>
          <div class="px-6 py-6">
            <div class="rounded-lg border-2 border-dashed border-gray-300 p-6 text-center text-sm text-gray-500 bg-gray-50">
              请先完成“创建产品”，随后在编辑页使用图片管理组件上传、设主图与排序。
            </div>
          </div>
        </div>

        <!-- 步骤控制按钮 -->
        <div class="flex justify-between">
          <button 
            v-if="currentStep > 0"
            type="button"
            @click="previousStep"
            class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200"
          >
            <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
            上一步
          </button>
          <div v-else></div>
          
          <div class="flex space-x-3">
            <Link :href="route('admin.products.index')" 
                  class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200">
              取消
            </Link>
            
            <button 
              v-if="currentStep < steps.length - 1"
              type="button"
              @click="nextStep"
              class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200"
            >
              下一步
              <svg class="-mr-1 ml-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
              </svg>
            </button>
            
            <button 
              v-else
              type="submit" 
              :disabled="processing"
              class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
            >
              <svg v-if="processing" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              {{ processing ? '创建中...' : '创建产品' }}
            </button>
          </div>
        </div>
      </form>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  categories: {
    type: Array,
    required: true
  },
  availableAttributes: {
    type: Array,
    default: () => []
  },
  specificationTemplates: {
    type: Array,
    default: () => []
  }
})

// 步骤配置
const steps = [
  { title: '基本信息', description: '填写产品基本信息、价格与状态' },
  { title: '分类模板', description: '选择分类和模板' },
  { title: '规格型号', description: '生成规格型号' }
]

// 当前步骤
const currentStep = ref(0)

// 步骤样式
const getStepClasses = (index) => {
  if (index < currentStep.value) {
    return 'bg-gray-900 text-white' // 已完成
  } else if (index === currentStep.value) {
    return 'bg-gray-900 text-white' // 当前步骤
  } else {
    return 'bg-gray-200 text-gray-600' // 未完成
  }
}

// 步骤控制
const nextStep = () => {
  if (currentStep.value < steps.length - 1) {
    currentStep.value++
  }
}

const previousStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const form = useForm({
  name: '',
  slug: '',
  sku: '',
  description: '',
  long_description: '',
  features: [],
  technical_specs: [],
  price: 0,
  compare_price: null,
  product_type: 'single',
  is_active: true,
  is_featured: false,
  stock_quantity: 0,
  category_ids: [],
  variants: [],
})

const processing = ref(false)
const selectedAttributes = ref([])
const generatedVariants = ref([])
const selectedTemplate = ref(null)
const { showError, showSuccess } = useNotification()

// 选择规格模板
const selectTemplate = (template) => {
  selectedTemplate.value = template
  // 清空手动选择的属性
  selectedAttributes.value = []
  // 清空已生成的规格型号
  generatedVariants.value = []
}

// 计算属性：根据已选分类筛选规格模板
const filteredTemplates = computed(() => {
  if (form.category_ids.length === 0) return []
  
  return props.specificationTemplates.filter(template => {
    // 全局模板始终显示
    if (!template.category_id) return true
    
    // 显示当前选中分类的专用模板
    return form.category_ids.includes(template.category_id)
  })
})

// 计算属性：规格型号总库存（前端实时计算）
const totalVariantStock = computed(() => {
  return generatedVariants.value.reduce((total, variant) => {
    return total + (variant.stock_quantity || 0)
  }, 0)
})

// 计算属性：规格型号库存统计详情
const variantStockStats = computed(() => {
  const stats = {
    total: 0,
    variants: generatedVariants.value.length,
    inStock: 0,
    outOfStock: 0,
    lowStock: 0
  }
  
  generatedVariants.value.forEach(variant => {
    const stock = variant.stock_quantity || 0
    stats.total += stock
    
    if (stock > 0) {
      stats.inStock++
    } else {
      stats.outOfStock++
    }
    
    if (stock > 0 && stock <= 5) { // 低库存阈值
      stats.lowStock++
    }
  })
  
  return stats
})

// 计算属性：获取属性名称
const getAttributeName = (attributeId) => {
  const attribute = props.availableAttributes.find(attr => attr.id === attributeId)
  return attribute ? attribute.name : '未知属性'
}

// 产品特性管理
const addFeature = () => {
  form.features.push('')
}

const removeFeature = (index) => {
  form.features.splice(index, 1)
}

// 技术规格管理
const addSpecCategory = () => {
  form.technical_specs.push({
    category: '',
    items: [{ name: '', value: '' }]
  })
}

const removeSpecCategory = (index) => {
  form.technical_specs.splice(index, 1)
}

const addSpecItem = (specIndex) => {
  form.technical_specs[specIndex].items.push({ name: '', value: '' })
}

const removeSpecItem = (specIndex, itemIndex) => {
  form.technical_specs[specIndex].items.splice(itemIndex, 1)
}

// 生成规格型号组合
const generateVariants = () => {
  // 如果选择了规格模板，使用模板中的属性
  if (selectedTemplate.value) {
    const templateAttributes = selectedTemplate.value.attributes_config || []
    if (templateAttributes.length === 0) return
    
    // 从模板生成规格型号
    const combinations = generateCombinations(templateAttributes)
    generatedVariants.value = combinations.map((combo, index) => ({
      sku: '',
      price: form.price,
      stock_quantity: 0,
      specifications: combo
    }))
    return
  }
  
  // 手动选择的属性
  if (selectedAttributes.value.length === 0) return
  
  const attributes = props.availableAttributes.filter(attr => 
    selectedAttributes.value.includes(attr.id)
  )
  
  // 生成笛卡尔积
  const combinations = generateCombinations(attributes)
  
  generatedVariants.value = combinations.map((combination, index) => ({
    sku: `SKU-${Date.now()}-${index + 1}`,
    price: form.price || 0,
    stock_quantity: 0,
    specifications: combination.map(attr => ({
      attribute_id: attr.id,
      value: '',
      display_value: '',
    }))
  }))
}

// 生成笛卡尔积
const generateCombinations = (attributes) => {
  if (attributes.length === 0) return []
  
  // 处理模板属性格式
  if (attributes[0].slug) {
    // 模板属性格式
    if (attributes.length === 1) {
      return attributes[0].options.map(option => [{
        attribute_id: attributes[0].slug,
        attribute_name: attributes[0].name,
        value: option.name || option.value || option,
        display_value: option.name || option.value || option
      }])
    }
    
    const result = []
    const first = attributes[0]
    const rest = generateCombinations(attributes.slice(1))
    
    first.options.forEach(option => {
      rest.forEach(combination => {
        result.push([{
          attribute_id: first.slug,
          attribute_name: first.name,
          value: option.name || option.value || option,
          display_value: option.name || option.value || option
        }, ...combination])
      })
    })
    
    return result
  } else {
    // 原有属性格式
    if (attributes.length === 1) {
      return attributes[0].options.map(option => [{
        attribute_id: attributes[0].id,
        attribute_name: attributes[0].name,
        value: option,
        display_value: option
      }])
    }
    
    const result = []
    const first = attributes[0]
    const rest = generateCombinations(attributes.slice(1))
    
    first.options.forEach(option => {
      rest.forEach(combination => {
        result.push([{
          attribute_id: first.id,
          attribute_name: first.name,
          value: option,
          display_value: option
        }, ...combination])
      })
    })
    
    return result
  }
}

// 移除规格型号
const removeVariant = (index) => {
  generatedVariants.value.splice(index, 1)
}

// 提交表单
const submit = () => {
  // 如果是多规格产品，将规格型号数据添加到表单中
  if (form.product_type === 'multi_variant') {
    form.variants = generatedVariants.value
  }
  
  processing.value = true
  form.post(route('admin.products.store'), {
    onSuccess: () => {
      processing.value = false
      // 后端已经发送了 flash 消息，这里不需要重复显示
    },
    onError: (errors) => {
      processing.value = false
      
      // 处理规格型号相关的错误
      const variantErrors = Object.keys(errors).filter(key => key.startsWith('variants.'))
      if (variantErrors.length > 0) {
        const firstVariantError = variantErrors[0]
        const errorMessage = errors[firstVariantError]
        showError('规格型号配置错误', Array.isArray(errorMessage) ? errorMessage[0] : errorMessage)
        return
      }
      
      // 显示第一个错误信息
      const firstError = Object.values(errors)[0]
      if (firstError) {
        showError('产品创建失败', Array.isArray(firstError) ? firstError[0] : firstError)
      } else {
        showError('产品创建失败', '请检查表单信息')
      }
    },
    onFinish: () => {
      processing.value = false
    }
  })
}

const errors = form.errors
</script>
